package com.example.interceptmybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.interceptmybatis.entity.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
@Slf4j
public class InjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        if(originalObject instanceof BaseEntity baseEntity){
            Class<? extends BaseEntity> aClass = baseEntity.getClass();
            List<Field> fieldList = Arrays.asList(aClass.getDeclaredFields());
            fieldList.forEach(field -> {
                setValue(field,"admin",metaObject.getOriginalObject(),v -> "createBy".equals(v.getName()));
                setValue(field, LocalDateTime.now(),metaObject.getOriginalObject(), v -> "createTime".equals(v.getName()));
            });
        }
    }

    private void setValue(Field field, Object value, Object target,Predicate<Field> predicate){
        if(predicate.test(field)){
            try {
                field.setAccessible(true);
                field.set(target,value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        if(originalObject instanceof BaseEntity baseEntity){
            Class<? extends BaseEntity> aClass = baseEntity.getClass();
            List<Field> fieldList = Arrays.asList(aClass.getDeclaredFields());
            fieldList.forEach(field -> {
                setValue(field,"admin",metaObject.getOriginalObject(),v -> "updateBy".equals(v.getName()));
                setValue(field, LocalDateTime.now(),metaObject.getOriginalObject(), v -> "updateTime".equals(v.getName()));
            });
        }
    }
}
